import React, {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from "react";
import TaskItem from "./TaskItem/TaskItem";
import { ITask } from "../../../types/task";

import * as S from "./styles";
import {
  FlatList,
  Modal,
  Pressable,
  RefreshControl,
  Text,
  TouchableWithoutFeedback,
  View,
} from "react-native";
import moment from "moment";
import { useTasks } from "../../../hooks/useTasks";
import { showToast } from "../../../utils/toast";
import { windowHeight, windowWidth } from "../../../utils/config";
import { DelModal } from "./confirm";
import { NativeBaseProvider } from "native-base";
import { TaskModal } from "../../../components/TaskModal";
import { useCategory } from "../../../hooks/useCategory";

export const TasksList = forwardRef((props, ref) => {
  const [refreshing, setRefreshing] = useState(false);
  const {
    tasks,
    loadTasks,
    deleteTask,
    updateSelectedTaskId,
    activeDate,
    updateActiveDate,
    startDate,
    endDate,
    updateEndDate,
    updateCreateModalVis,
    createModalVis,
    quickVisible,
    selectedTaskId,
  } = useTasks();

  const listRef = useRef(null);

  const initDate = moment(startDate).subtract(12, "days").format("YYYY-MM-DD");
  const [refreshDate, setRefreshDate] = useState(initDate);
  // const [operateItem, setOperateItem] = useState(null);
  const [visable, setVisible] = useState(false);
  const [modalVisibleDel, setModalVisibleDel] = useState(false);
  const [offset, setOffset] = useState([]);

  const onEndReached = useCallback(() => {
    setRefreshing(true);
    let date = refreshDate;
    // console.log("re--", startDate, refreshDate);
    if (moment(startDate).isBefore(moment(refreshDate))) {
      date = moment(startDate).subtract(12, "days").format("YYYY-MM-DD");
    }

    loadTasks({
      startDate: date,
      endDate: startDate,
    }).then(function (response) {
      setRefreshDate(moment(date).subtract(6, "days").format("YYYY-MM-DD"));
      updateEndDate(moment(date).subtract(6, "days").format("YYYY-MM-DD"));
      // listRef.current.scrollToIndex({ index: 6 });
      setRefreshing(false);
      if (createModalVis || quickVisible) {
        scrollToActive();
      }
    });
  }, [createModalVis, loadTasks, quickVisible, refreshDate, scrollToActive, startDate, updateEndDate]);

  const scrollToActive = useCallback(() => {
    let height = 0;
    offset.forEach((off, index) => {
      if (
        moment(off.date).isAfter(moment(activeDate)) &&
        moment(off.date).isSameOrBefore(moment(startDate))
      ) {
        height += off.height;
      }
    });
    listRef?.current?.scrollToOffset({ offset: height });
  }, [activeDate, offset, startDate]);

  useImperativeHandle(ref, () => ({
    scroll: scrollToActive,
    scrollToTop: () => {
      listRef?.current?.scrollToOffset({ offset: 0 });
    },
  }));

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    // console.log("refresh---", refreshDate, startDate);
    loadTasks({
      startDate: moment(startDate).subtract(6, "days").format("YYYY-MM-DD"),
      endDate: startDate,
    }).then(function (response) {
      // listRef.current.scrollToIndex({ index: 6 });
      setRefreshing(false);
    });
  }, [loadTasks, startDate]);

  useEffect(() => {
    loadTasks({
      startDate: moment(startDate).subtract(6, "days").format("YYYY-MM-DD"),
      endDate: moment(startDate).format("YYYY-MM-DD"),
    });
  }, []);

  const handleActived = useCallback(
    (v) => {
      updateActiveDate(v);
    },
    [updateActiveDate]
  );

  const handleOperated = useCallback(
    (v) => {
      // setOperateItem(v);
      updateSelectedTaskId(v);
      updateActiveDate(v?.date);
      setVisible(true);
    },
    [updateActiveDate, updateSelectedTaskId]
  );

  const handleLayout = useCallback(
    (v) => {
      const list = offset.filter((off) => off.date !== v.date);
      setOffset([v, ...list]);
    },
    [offset]
  );
  // const item = taskList.length > 0 ? taskList[0].date : null;
  const renderItem = useCallback(
    ({ item }: { item: ITask }) => {
      return (
        <TaskItem
          {...item}
          onLayout={handleLayout}
          hasOperated={item.date === selectedTaskId?.date}
          hasActived={item.date === activeDate}
          onActive={handleActived}
          onLongPress={handleOperated}
        />
      );
    },
    [
      activeDate,
      handleActived,
      handleLayout,
      handleOperated,
      selectedTaskId?.date,
    ]
  );

  const delRecord = () => {
    deleteTask({ id: selectedTaskId?.id }).then((res) => {
      showToast("success", "提示", "删除记录成功");
      loadTasks({
        startDate: moment(endDate).format("YYYY-MM-DD"),
        endDate: moment(startDate).format("YYYY-MM-DD"),
      });
      setModalVisibleDel(false);
      updateSelectedTaskId(null);
    });
  };

  return (
    <S.Container>
      <DelModal
        bucketDelFun={delRecord}
        modalVisible={modalVisibleDel}
        setModalVisible={setModalVisibleDel}
      />
      <Modal
        animationType="fade"
        presentationStyle="overFullScreen"
        transparent={true}
        visible={visable}
      >
        <TouchableWithoutFeedback
          onPress={() => {
            updateSelectedTaskId(null);
            setVisible(false);
          }}
        >
          <S.ModalOverlay>
            <S.ModalView>
              <Pressable
                onPress={() => {
                  // updateSelectedTaskId(operateItem);
                  scrollToActive();
                  setVisible(false);
                  updateCreateModalVis(true);
                }}
              >
                <View
                  style={{
                    height: /*RFValue*/ 48,
                    width: windowWidth,
                    alignItems: "center",
                    padding: /*RFValue*/ 12,
                    borderBottom: "1px solid rgba(231, 230, 228, 1)",
                  }}
                >
                  <Text
                    style={{
                      fontFamily: "HarmonyOS_Sans_SC_Regular",
                      color: "rgba(44, 44, 46, 1)",
                      fontSize: /*RFValue*/ 16,
                      fontWeight: 400,
                    }}
                  >
                    编辑
                  </Text>
                </View>
              </Pressable>
              <View
                style={{
                  width: windowWidth,
                  height: /*RFValue*/ 2,
                  backgroundColor: "rgba(243, 244, 246, 1)",
                }}
              ></View>
              <Pressable
                onPress={() => {
                  setVisible(false);
                  setModalVisibleDel(true);
                }}
                style={{
                  height: /*RFValue*/ 48,
                  width: "100%",
                  alignItems: "center",
                  padding: /*RFValue*/ 12,
                }}
              >
                <Text
                  style={{
                    color: "rgba(227, 73, 73, 1)",
                    fontFamily: "HarmonyOS_Sans_SC_Regular",
                    fontSize: /*RFValue*/ 16,
                    fontWeight: 400,
                  }}
                >
                  删除
                </Text>
              </Pressable>
              <View
                style={{
                  width: "100%",
                  height: /*RFValue*/ 8,
                  backgroundColor: "rgba(243, 244, 246, 1)",
                }}
              ></View>
              <Pressable
                onPress={() => {
                  updateSelectedTaskId(null);
                  setVisible(false);
                }}
                style={{
                  height: /*RFValue*/ 48,
                  width: windowWidth,
                  alignItems: "center",
                  padding: /*RFValue*/ 12,
                  fontFamily: "HarmonyOS_Sans_SC_Regular",
                }}
              >
                <Text
                  style={{
                    fontSize: /*RFValue*/ 16,
                    fontWeight: 400,
                    color: "rgba(44, 44, 46, 1)",
                  }}
                >
                  取消
                </Text>
              </Pressable>
            </S.ModalView>
          </S.ModalOverlay>
        </TouchableWithoutFeedback>
      </Modal>
      {createModalVis && (
        <TaskModal
          title="记录"
          // operatedRecord={operateItem}
          toggleModal={() => updateCreateModalVis(false)}
          onCancel={() => updateCreateModalVis(false)}
          visible={createModalVis}
        />
      )}
      <FlatList
        ref={listRef}
        data={tasks}
        style={{ flex: 1 }}
        progressViewOffset={172}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor="rgba(67, 113, 177, 1)"
            // title="Loading..."
            // titleColor="rgba(198, 224, 247, 1)"
            // size={0}
            colors={["rgba(67, 113, 177, 1)"]}
            progressBackgroundColor="white"
          />
        }
        onEndReached={onEndReached}
        onEndReachedThreshold={0.1}
        renderItem={renderItem}
        keyExtractor={(item) => String(item.date)}
        // getItemLayout={(data, index) => ({
        //   length: 100,
        //   offset: 100 * index,
        //   index,
        // })}
        showsVerticalScrollIndicator={false}
        // style={{ marginBottom: 20 }}
      />
    </S.Container>
  );
});
